import pandas as pd
import webbrowser
from pyecharts.charts import Pie, Bar
from pyecharts import options as opts

air_file_path = "data/北京空气质量近十年_2015到2025.xlsx"
sheet_names = ['2015', '2016', '2017', '2018', '2019', '2020', '2021', '2022', '2023', '2024', '2025']
combined_air_data = []

for year in sheet_names:
    df = pd.read_excel(air_file_path, sheet_name=year)
    df['日期'] = pd.to_datetime(df['日期'], errors='coerce')
    df['AQI指数'] = pd.to_numeric(df['AQI指数'], errors='coerce')
    combined_air_data.append(df[['日期', 'AQI指数', '质量等级', 'PM2.5', 'PM10', 'So2', 'No2', 'Co', 'O3']])

df_air = pd.concat(combined_air_data, ignore_index=True).dropna()

weather_file_path = "data/北京天气近十年_2015到2025.xlsx"
combined_weather_data = []

for year in sheet_names:
    df = pd.read_excel(weather_file_path, sheet_name=year)
    df['日期'] = pd.to_datetime(df['日期'], errors='coerce')
    # 提取风向和风力
    df['风向'] = df['风力风向'].str.extract(r'([东南西北]+风)')[0]
    df['风力'] = df['风力风向'].str.extract(r'(\d-\d)级')[0]
    combined_weather_data.append(df[['日期', '天气状况', '气温', '风向', '风力']])

df_weather = pd.concat(combined_weather_data, ignore_index=True).dropna()

df_all = pd.merge(df_air, df_weather, on='日期', how='left')


def set_global_options(chart, title):
    chart.set_global_opts(
        title_opts=opts.TitleOpts(
            title=title,
            title_textstyle_opts=opts.TextStyleOpts(
                color="#000",  # ✅ 黑色字体
                font_size=18,
                font_weight="bold"
            ),
            pos_left="center",
            pos_top="5%"  # 推荐稍下移，避免遮挡
        ),
        legend_opts=opts.LegendOpts(
            textstyle_opts=opts.TextStyleOpts(color="#000"),
            pos_bottom="50px",  # 图例放置在底部
            orient="horizontal"
        ),
        tooltip_opts=opts.TooltipOpts(
            background_color="rgba(255,255,255,0.9)",  # 白底
            border_color="rgba(0,0,0,0.2)",
            textstyle_opts=opts.TextStyleOpts(color="#000")  # ✅ 黑字
        )
    )
    return chart


# 风向频率分布
wind_directions = ['东风', '南风', '西风', '北风', '东南风', '西南风', '西北风', '东北风']
wind_df = df_all[df_all['风向'].isin(wind_directions)]
wind_count = wind_df['风向'].value_counts().reset_index()
wind_count.columns = ['direction', 'count']

wind_chart = (
    Pie(init_opts=opts.InitOpts(width="900px", height="600px", bg_color="white"))
    .add(
        "",
        [list(z) for z in zip(wind_count['direction'], wind_count['count'])],
        radius=["30%", "70%"],
        label_opts=opts.LabelOpts(
            formatter="{b}: {c} ({d}%)",
            color="#000"
        ),
        rosetype="radius"
    )
)

wind_chart = set_global_options(
    wind_chart,
    ""
)


wind_speed_count = df_all['风力'].value_counts().reset_index()
wind_speed_count.columns = ['speed', 'count']

wind_speed_chart = (
    Bar(init_opts=opts.InitOpts(width="900px", height="600px", bg_color="white"))
    .add_xaxis(wind_speed_count['speed'].tolist())
    .add_yaxis(
        "出现次数",
        wind_speed_count['count'].tolist(),
        itemstyle_opts=opts.ItemStyleOpts(color="#91CC75")
    )
    .set_series_opts(
        label_opts=opts.LabelOpts(
            is_show=True,
            position="top",
            color="#000"
        )
    )
)

wind_speed_chart = set_global_options(
    wind_speed_chart,
    "风力等级分布"
).set_global_opts(
    yaxis_opts=opts.AxisOpts(
        name="出现次数",
        axislabel_opts=opts.LabelOpts(color="#000")
    ),
    xaxis_opts=opts.AxisOpts(
        name="风力等级",
        axislabel_opts=opts.LabelOpts(color="#000")
    ),
    toolbox_opts=opts.ToolboxOpts(),
)

output_path = "wind_rose.html"
wind_chart.render(output_path)
webbrowser.open(output_path)
